﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Management;
using System.Security.Cryptography;
using System.Collections;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;

namespace SecurityDev
{
    
    public partial class Authorization : Form
    {
        private string code = FingerPrint.Value();
        string company = null;
        string accessKey = "AKIAIOPVPT5WPQ7CIWGQ";
        string secretKey = "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";

        public Authorization()
        {
            InitializeComponent();
            label4.Visible = false;
            label4.ForeColor = Color.Red;
            label5.Visible = false;
            textBox1.Visible = false;
            label6.Visible = false;
            button2.Visible = false;
            label7.Visible = false;
            label8.Visible = false;
            label9.Visible = false;
            label11.Visible = false;
            label8.ForeColor = Color.Red;
            label9.ForeColor = Color.Red;
            label11.ForeColor = Color.Red;
            progressBar1.Visible = false;
            progressBar1.ForeColor = Color.SeaGreen;
        }

       private void button1_Click(object sender, EventArgs e)
        {
            if (nameBox.Text == "")
            {
                label8.Visible = true;
            } else
            {
                label8.Visible = false;
            }
            if (LastNameBox.Text == "")
            {
                label9.Visible = true;
            } else
            {
                label9.Visible = false;
            }

            if (companyBox.Text == "")
            {
                label11.Visible = true;
            } else
            {
                label11.Visible = false;
            }

            if (EmailBox.Text == "")
            {
                 label4.Visible = true;
                 label4.Text = "Please Enter Email";
            }
            if (!IsValidEmail(EmailBox.Text))
            {
                if (EmailBox.Text != "")
                {
                    label4.Visible = true;
                    label4.Text = "Invalid Email Format";
                }
                else
                {
                    label4.Visible = true;
                    label4.Text = "Please Enter Email";
                }
            }
            else
            {
                if (button1.Text != "Finish" && IsValidEmail(EmailBox.Text) && EmailBox.Text != "" && companyBox.Text != "" && nameBox.Text != "" && LastNameBox.Text != "")
                {
                    progressBar1.Visible = true;
                    progressBar1.Maximum = 100;
                    backgroundWorker1.WorkerReportsProgress = true;
                    backgroundWorker1.RunWorkerAsync();
                    company = companyBox.Text;
                    button1.Enabled = false;
                    label4.Visible = false;
                }
                
               label4.Visible = false;
               label8.Visible = false;
               label9.Visible = false;
               label11.Visible = false; 
                if (companyBox.Text != "" && nameBox.Text != "" && LastNameBox.Text != "" && EmailBox.Text != "")
                {
                    nameBox.Enabled = false;
                    LastNameBox.Enabled = false;
                    EmailBox.Enabled = false;
                    companyBox.Enabled = false;
                }
                string entered_code = textBox1.Text;
                if (this.code != entered_code && entered_code != "" && button1.Text == "Finish")
                {
                    label6.ForeColor = Color.Red;
                    label6.Visible = true;
                }

                if (button1.Text == "Finish" && entered_code != "" && code == entered_code)
                {
                    button2.Visible = true;
                    label7.Visible = true;
                    label7.Text += ", please check email, " + @Environment.NewLine +
                        "                 you've just received default user access.";
                    button1.Visible = false;
                    label6.Visible = false;
                    label5.Visible = false;
                    textBox1.Visible = false;
                    label4.Visible = false;
                    nameBox.Enabled = false;
                    LastNameBox.Enabled = false;
                    EmailBox.Enabled = false;
                    companyBox.Enabled = false;

                    AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey,secretKey);
                    /* PutBucketRequest request = new PutBucketRequest();
                    request.BucketName = company.ToLower();
                    request.BucketRegion = S3Region.EU;
                    request.CannedACL = S3CannedACL.PublicRead; // make bucket publicly readable
                    client.PutBucket(request);  */

                    try
                    {
                        PutBucketRequest request = new PutBucketRequest();
                        request.WithBucketName(company.ToLower())
                               .WithBucketRegion(S3Region.EU)
                               .WithCannedACL(S3CannedACL.PublicReadWrite);
                        client.PutBucket(request);
                    }
                    catch (AmazonS3Exception amazonS3Exception)
                    {
                        if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                        {
                            MessageBox.Show("Please check the provided SecureInfo Credentials.");
                        }
                        else
                        {
                            MessageBox.Show("Please check the provided SecureInfo Credentials.");
                        }
                    }
                }
            }
        }

       private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
       {
           Thread t = new Thread(sendEmail);
           t.Start();

           for (int i = 0; i <= 100; i++)
           {
               backgroundWorker1.ReportProgress(i);
               Thread.Sleep(8);
           }
       }

       private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
       {
           progressBar1.Value = e.ProgressPercentage;
       }

       private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
       {
           button1.Enabled = true;
           progressBar1.Visible = false;
           button1.Text = "Finish";
           label5.Visible = true;
           textBox1.Visible = true;
       }

       private void EmailBox_TextChanged(object sender, EventArgs e)
       {
       }

        private void button2_Click(object sender, EventArgs e)
        {
            string windir_path = @Environment.GetEnvironmentVariable("windir") + "/SecureInfo.dat";
            if (!File.Exists(windir_path))
            {
                File.WriteAllText(@Environment.GetEnvironmentVariable("windir") + "/SecureInfo.dat", Encrypt(code, "123456", true));
                File.SetAttributes(@Environment.GetEnvironmentVariable("windir") + "/SecureInfo.dat", FileAttributes.Hidden);
            }
            string path = @"config" + "/" + "configuration.dat";
            if (!File.Exists(path))
            {
              File.WriteAllText(path,
                "company: " + companyBox.Text + @Environment.NewLine +
                "name: " + nameBox.Text + @Environment.NewLine + 
                "last name: " + LastNameBox.Text + @Environment.NewLine +
                "email: " + EmailBox.Text + @Environment.NewLine);
              File.SetAttributes(path, FileAttributes.Hidden);
            }
            Users us = new Users();
            //mycomm//us.AddUser_Click(sender, e, "admin", "12345", "admin");
            us.Close();
            this.button2.Visible = false;
            
            var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            var ip = (from addr in hostEntry.AddressList
                      where addr.AddressFamily.ToString() == "InterNetwork"
                      select addr.ToString()).FirstOrDefault();
            if (ip == null) ip = "";
            const string subject = "SecurInfo Registration Email";
            string body = "Dear <b>" + nameBox.Text + " " + LastNameBox.Text + "</b> from company <b> " + companyBox.Text + "</b>, " +
                "you've received the next user to access: " + 
                "<br> Login: <b> admin </b> <br> Password: <b> 12345 </b> " + 
                "<br> <br> Best regards, <br> SecureInfo <br>";

            List<string> ToEmailAddresses = new List<string>();
            ToEmailAddresses.Add(EmailBox.Text);
            var client = new AmazonSimpleEmailServiceClient("AKIAIOPVPT5WPQ7CIWGQ", "mub7xYzBD/6VkgxIkyQY0U+6m9DSGTWs74bP6AzM");
            Body bdy = new Body();
            bdy.Html = new Amazon.SimpleEmail.Model.Content(body);
            SendEmailRequest req = new SendEmailRequest()
                .WithDestination(new Destination() { ToAddresses = ToEmailAddresses })
                .WithSource("noreply@securitydev.com.ua")
                .WithReturnPath("noreply@securitydev.com.ua")
                .WithMessage(
                new Amazon.SimpleEmail.Model.Message(new Content("SecurInfo Registration Email"),
                bdy));

            var resp = client.SendEmail(req);

            Close();
            Application.Exit();
        }
        public bool IsValidEmail(string strIn)
        {
            // Return true if strIn is in valid e-mail format.
            return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        public static string Encrypt(string toEncrypt, string key, bool useHashing)
        {
            byte[] buffer;
            byte[] bytes = Encoding.UTF8.GetBytes(toEncrypt);
            if (useHashing)
            {
                buffer = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(key));
            }
            else
            {
                buffer = Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider
            {
                Key = buffer,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] inArray = provider2.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
            return Convert.ToBase64String(inArray, 0, inArray.Length);
        }

        // send Email
        public void sendEmail()
        {
            var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            var ip = (from addr in hostEntry.AddressList
                      where addr.AddressFamily.ToString() == "InterNetwork"
                      select addr.ToString()).FirstOrDefault();
            if (ip == null) ip = "";
            string body = "Dear <b>" + nameBox.Text + " " + LastNameBox.Text + "</b> from company <b> " + companyBox.Text + "</b>, please confirm your registration "
                          + "with this code: <br> <br>" + this.code + "<br> <br> Best regards, <br> SecureInfo <br>";

            string bodyus = "New client from company: <b> " + companyBox.Text + "</b>  <br>" +
                   "Name: " + nameBox.Text + " " + LastNameBox.Text + "<br>" +
                   "Email: " + EmailBox.Text + "<br>" +
                   "Time of registration: " + DateTime.Now + "<br>" +
                   "IP: " + ip + "<br>" +
                   "Received next password: " + this.code + "<br>";


            List<string> ToEmailAddresses = new List<string>();
            ToEmailAddresses.Add(EmailBox.Text);

            var client = new AmazonSimpleEmailServiceClient("AKIAIOPVPT5WPQ7CIWGQ", "mub7xYzBD/6VkgxIkyQY0U+6m9DSGTWs74bP6AzM");
            Body bdy = new Body();
            bdy.Html = new Amazon.SimpleEmail.Model.Content(body);
            SendEmailRequest req = new SendEmailRequest()
                .WithDestination(new Destination() { ToAddresses = ToEmailAddresses })
                .WithSource("noreply@securitydev.com.ua")
                .WithReturnPath("noreply@securitydev.com.ua")
                .WithMessage(
                new Amazon.SimpleEmail.Model.Message(new Content("SecurInfo Registration Email"),
                bdy));

            var resp = client.SendEmail(req);

           ToEmailAddresses.Clear();
            ToEmailAddresses.Add("registration@securitydev.com.ua");
            Body bdyus = new Body();
            bdyus.Html = new Amazon.SimpleEmail.Model.Content(bodyus);
            SendEmailRequest requs = new SendEmailRequest()
                .WithDestination(new Destination() { ToAddresses = ToEmailAddresses })
                .WithSource("noreply@securitydev.com.ua")
                .WithReturnPath("noreply@securitydev.com.ua")
                .WithMessage(
                new Amazon.SimpleEmail.Model.Message(new Content("SecurInfo Registration Email"),
                bdyus));

            var respus = client.SendEmail(req); 
            }

        }

    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// </summary>
    public class FingerPrint
    {
        private static string fingerPrint = string.Empty;
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " +
            biosId() + "\nBASE >> " + baseId() + videoId() + "\nMAC >> " + macId());
            }
            return fingerPrint;
        }
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            ManagementClass mc = new ManagementClass(wmiClass);
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            ManagementClass mc = new ManagementClass(wmiClass);
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration",
                "MACAddress", "IPEnabled");
        }
        #endregion
    }

    }

  
